package com.liming.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liming.server.domain.Teacher;
import com.liming.server.domain.TeacherExample;
import com.liming.server.dto.TeacherDto;
import com.liming.server.dto.PageDto;
import com.liming.server.mapper.TeacherMapper;
import com.liming.server.util.CopyUtil;
import com.liming.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    public List<TeacherDto> all(){
        TeacherExample teacherExample = new TeacherExample();
        List<Teacher> teacherList = teacherMapper.selectByExample(teacherExample);
        //将teacherList通过CopyUtil.copyList()方法复制给teacherDtoList
        return CopyUtil.copyList(teacherList,TeacherDto.class);
    }

    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        TeacherExample teacherExample = new TeacherExample();
        List<Teacher> teacherList = teacherMapper.selectByExample(teacherExample);
        PageInfo<Teacher> pageInfo = new PageInfo<>(teacherList);
        pageDto.setTotal(pageInfo.getTotal());
        //将teacherList通过CopyUtil.copyList()方法复制给teacherDtoList
        List<TeacherDto> teacherDtoList =CopyUtil.copyList(teacherList,TeacherDto.class);
        pageDto.setList(teacherDtoList);
    }

    public void save(TeacherDto teacherDto){
        //将teacherDto通过CopyUtil.copy()方法复制给Teacher
        Teacher teacher = CopyUtil.copy(teacherDto, Teacher.class);
        if(StringUtils.isEmpty(teacherDto.getId())){
            this.insert(teacher);
        }else{
            this.update(teacher);
        }
    }

    private void insert(Teacher teacher){

        teacher.setId(UuidUtil.getShortUuid());
        teacherMapper.insert(teacher);
    }
    private void update(Teacher teacher){
        teacherMapper.updateByPrimaryKey(teacher);
    }

    public void delete(String id){
        teacherMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查找讲师的课程
     */
    public TeacherDto findById(String id) {
        Teacher teacher = teacherMapper.selectByPrimaryKey(id);
        return CopyUtil.copy(teacher,TeacherDto.class);
    }
}